<template>
  <PlusDialogForm
    ref="formRef"
    v-model:visible="visible"
    v-model="form"
    :form="{ columns, labelWidth: 120, labelPosition: 'right' }"
    :dialog="{ title }"
    @confirm="submit"
  >
    <template #plus-field-userIdList>
      <div style="width: 100%">
        <el-tag
          v-for="(item, index) in chooseUserItems"
          :key="item.userId"
          closable
          class="mb-2 mr-2"
          size="large"
          @close="delUser(item, index)"
          >{{ item.userName }}</el-tag
        >
      </div>

      <el-button type="primary" @click="openUser">选择用户</el-button>
      <el-button type="success" @click="openAddUser">新增用户</el-button>
    </template>
  </PlusDialogForm>
  <chooseUser ref="chooseUserRef" @confirm="getUserData" />

  <addUser ref="addUserRef" :online="false" @confirm="addUerData" />
</template>
<script setup lang="tsx">
import { ref, nextTick, computed } from "vue";
import { ElMessage } from "element-plus";
import {
  type PlusColumn,
  type FieldValues,
  PlusDialogForm
} from "plus-pro-components";

import chooseUser from "@/components/chooseUser/index.vue";

import { addApi, editApi } from "@/api/warehouse/index";
import { deWeightArr } from "@/utils";
import addUser from "@/views/system/user/modules/operate.vue";

const columns = ref();

// 弹窗操作
const visible = ref(false);
const formRef = ref(null);

const title = computed(() => {
  return isEdit.value ? "设置工具室" : "新增工具室";
});

/* 表单操作 */
const form = ref<FieldValues>({
  name: "",
  userIdList: []
});
const emit = defineEmits(["confirm"]);
const submit = value => {
  if (!(chooseUserItems.value as any).length) {
    return ElMessage.error("请选择管理员");
  }
  const httpApi = isEdit.value ? editApi : addApi;
  // 需要新增的用户列表
  const addUserList = chooseUserItems.value.filter(ele => ele.userId < 0);
  const params = {
    ...form.value
  };
  if (params?.createTime) {
    delete params.createTime;
  }

  httpApi(params).then(res => {
    ElMessage.success(`${title.value}成功`);

    visible.value = false;

    const data = { ...res } as any;
    // 新增用户
    if (addUserList.length) {
      Promise.all(
        addUserList.map(item =>
          userAddApi.value({
            ...item,
            warehouseId: data.data || form.value.warehouseId,
            userId: null
          })
        )
      ).then(ress => {
        console.log("新增用户", ress);
        emit("confirm", isEdit.value);
      });
    } else {
      emit("confirm", isEdit.value);
    }
  });
};

// 选人
const chooseUserItems = ref([]);
const chooseUserRef = ref<any>();
const openUser = () => {
  chooseUserRef.value.show();
};
const getUserData = (res = []) => {
  const addUser = chooseUserItems.value.filter(ele => ele.userId < 0);
  const list = [...res, ...chooseUserItems.value].filter(ele => ele.userId > 0);
  const userids = [...(form.value.userIdList as any)];
  res.map(item => {
    if (item.userId && item.userId > 0) {
      userids.push(item.userId);
    }
  });
  form.value.userIdList = Array.from(new Set(userids));

  chooseUserItems.value = deWeightArr(list, "userId");
  chooseUserItems.value.push(...addUser);
};

const delUser = (item, index) => {
  chooseUserItems.value.splice(index, 1);
  form.value.userIdList = chooseUserItems.value.map(item => item.userId);
};

/* 新增用户 */
const addUserRef = ref(null);
const openAddUser = () => {
  addUserRef?.value?.show();
};
const userAddApi = ref(null);
const addUerData = ({ params, addApi }) => {
  userAddApi.value = addApi;
  chooseUserItems.value.push({ ...params, userId: -1 });
};

/* 编辑 - 数据初始化 */
const isEdit = ref(false);
const initData = formdata => {
  const arr = [
    {
      label: "联网状态",
      prop: "networkState",
      valueType: "text",
      renderField: value => (value == 1 ? "在线" : " 下线")
    },
    {
      label: "使用状态",
      prop: "state",
      renderField: value => (value == 1 ? "使用中" : " 停用")
    },
    { label: "货架数量", prop: "facilityCount", valueType: "text" },
    { label: "添加时间", prop: "createTime", valueType: "text" }
  ];
  columns.value.push(...arr);
  const {
    endpointId,
    warehouseId,
    state,
    facilityCount,
    createTime,
    networkState,
    name
  } = formdata;
  form.value = {
    endpointId,
    warehouseId,
    state,
    facilityCount,
    createTime,
    networkState,
    name,
    userIdList: formdata?.sysUserVoList.map(item => item.userId)
  };

  chooseUserItems.value = formdata?.sysUserVoList.map(item => ({
    userId: item.userId,
    userName: item.userName
  }));
};

/* 初始化 */
const show = formdata => {
  isEdit.value = formdata ? true : false;
  chooseUserItems.value = [];

  nextTick(() => {
    formRef?.value?.formInstance?.clearValidate();
    form.value = {
      name: "",
      endpointId: "",
      userIdList: []
    };
  });

  columns.value = [
    {
      label: "工具室名称",
      prop: "name",
      rules: {
        required: true,
        message: "请输入工具室名称",
        trigger: "blur"
      }
    },
    {
      label: "管理员",
      prop: "userIdList"
    }
  ];
  if (formdata) {
    columns.value.unshift({
      label: "工具室编号",
      prop: "endpointId",
      valueType: "text"
    });
  } else {
    columns.value.unshift({
      label: "工具室编号",
      prop: "endpointId",
      rules: { required: true, message: "请填写工具室序列号", trigger: "blur" }
    });
  }
  /* formdata 有值则为编辑 */
  nextTick(() => {
    formdata && initData(formdata);
  });

  visible.value = true;
};
defineExpose({ show });
</script>
